package com.kenyi.co.ui.classification;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.kenyi.co.R;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.ui.classification.adapter.ClassificationRightAdapter;
import com.kenyi.co.ui.classification.bean.CategoryListBean;
import com.kenyi.co.ui.classification.bean.CategoryMainBean;
import com.kenyi.co.ui.classification.bean.CategoryMoreBean;
import com.kenyi.co.utils.CommonUtils;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;
import com.kenyi.co.utils.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class ClassificationRightFragment extends Fragment {
    private View view;

    private ImageView iv_fenlei_header;
    private RelativeLayout li_home_vier2;
    private int page = 0;
    private int code = 1;
    private int itemSize = 0;
    private ClassificationRightAdapter mDataAdapter = null;
    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;
    private LRecyclerView mRecyclerView = null;

    private View mEmptyView;
    private CategoryMainBean.DatasBean info;
    private Boolean is_end = false;
    private String userFav = "0";

    @Override
    public void onResume() {
        super.onResume();

        if (!userFav.equals(getFav())&&!userFav.equals("0")) {
            page = 0;
            mDataAdapter.clear();
            mLRecyclerViewAdapter.notifyDataSetChanged();
            getCategoryList(info.getShowName());

        }


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        view = inflater.inflate(R.layout.fragment_fenlei_right, null);

        //得到数据
        info = (CategoryMainBean.DatasBean) getArguments().getSerializable("info");

        mEmptyView = view.findViewById(R.id.empty_view);
        mRecyclerView = (LRecyclerView) view.findViewById(R.id.list);
        mDataAdapter = new ClassificationRightAdapter(getActivity());
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mLRecyclerViewAdapter);
        DividerDecoration divider = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.common_30dp)
                .setPadding(R.dimen.default_divider_padding_10)
                .setColorResource(R.color.white)
                .build();
        mRecyclerView.addItemDecoration(divider);
        LinearLayout adView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.classification_main_header, null);
        iv_fenlei_header = adView.findViewById(R.id.iv_fenlei_header);
        li_home_vier2 = adView.findViewById(R.id.li_home_vier);
        ViewGroup.LayoutParams vParams2 = li_home_vier2.getLayoutParams();
        float density = getResources().getDisplayMetrics().density;//dp转px
        int biankaung = (int) (60 * density + 0.5);
        vParams2.height = (int) ((CommonUtils.getMobileWidth(getActivity()) * 0.875 - biankaung) * 0.33);
        vParams2.width = (int) (CommonUtils.getMobileWidth(getActivity()) * 0.875 - biankaung);
        li_home_vier2.setLayoutParams(vParams2);
        mLRecyclerViewAdapter.addHeaderView(adView);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
//        getCategoryList(info.getShowName());
        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能

        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mRecyclerView.setLoadMoreEnabled(true);
        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {

                if (!is_end) {
                    page++;
                    getCategoryMore(info.getShowName(), page);
                } else {
                    mRecyclerView.setNoMore(true);
                }
            }
        });
        mRecyclerView.refresh();
        getCategoryList(info.getShowName());
        return view;
    }

    /**
     * 获取分类的资源
     */
    public void getCategoryList(String name) {

        Map<String, String> params = new HashMap<>();
        String myFav = getFav();
        params.put("tags", name);
        if (StringUtils.isNotEmptypro(myFav) && "推荐".equals(name)) {
            params.put("fav", myFav);
        }

        String url = NetConfig.CATEGORY_LIST;
        OkHttpUtils.get()
                .url(url)
                .params(params)

                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        CategoryListBean packlist = gson.fromJson(response, CategoryListBean.class);
                        int code = packlist.getCode();

                        List<CategoryListBean.DatasBean.ArticlesBean> itemListharticle;
                        List<CategoryListBean.DatasBean.ArticlesBean> itemListharticle2;
                        CategoryListBean.DatasBean article = new CategoryListBean.DatasBean();
                        CategoryListBean.DatasBean article2 = new CategoryListBean.DatasBean();


                        if (code == 200) {
                            itemListharticle2 = packlist.getDatas().getHotArticles();
                            for (int i = 0; i < itemListharticle2.size(); i++) {
                                itemListharticle2.get(i).setItemType(2);
                            }
                            itemSize = itemListharticle2.size();
                            mLRecyclerViewAdapter.setSpanSizeLookup(new LRecyclerViewAdapter.SpanSizeLookup() {
                                @Override
                                public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                                    if (position > (itemSize - 1)) {
                                        return gridLayoutManager.getSpanCount();
                                    } else {
                                        return 1;
                                    }

                                }
                            });
                            mDataAdapter.addAll(itemListharticle2);
                            article2.setArticles(itemListharticle2);

                            itemListharticle = packlist.getDatas().getArticles();

                            mDataAdapter.addAll(itemListharticle);
                            if (itemListharticle != null && itemListharticle.size() > 0) {
                                try {
                                    if (Util.isOnMainThread() && getActivity() != null) {
                                        if (StringUtils.isNotEmptypro(packlist.getDatas().getDefaultImg())) {
                                            Glide.with(getActivity())
                                                    .load(packlist.getDatas().getDefaultImg())
                                                    .into(iv_fenlei_header);
                                        } else {
                                            li_home_vier2.setVisibility(View.GONE);
                                        }

                                    }
                                } catch (Exception e) {
                                }

                                mRecyclerView.setVisibility(View.VISIBLE);
                                mEmptyView.setVisibility(View.GONE);

                            } else {

                                mRecyclerView.setVisibility(View.GONE);
                                mEmptyView.setVisibility(View.VISIBLE);
                            }

                        }
                    }
                });
    }

    public String getFav() {
        List<String> LikeTags;
        try {
            LikeTags = SharepUtils.getShDataList(getActivity(), SharepUtils.USER_FAV_TAGS_LIST, String.class);
            String tags = "";
            if (LikeTags != null && LikeTags.size() > 0) {
                for (int i = 0; i < LikeTags.size(); i++) {
                    if (i == 0) {
                        tags = LikeTags.get(i);
                    }
                    if (i == 1) {
                        tags = tags + "|" + LikeTags.get(i);
                    }
                    if (i == 2) {
                        tags = tags + "|" + LikeTags.get(i);
                    }
                }
                return tags;

            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取分类的更多资源
     */
    public void getCategoryMore(String tags, final int page) {

        Gson gson = new Gson();
        Map<Object, Object> map = new HashMap<>();

        map.put("pagecount", page);
        String str = gson.toJson(map);
        String url = NetConfig.CATEGORY_MORE + "?tags=" + tags;

        String myFav = getFav();
        if (StringUtils.isNotEmptypro(myFav)) {

            url = NetConfig.CATEGORY_MORE + "?tags=" + tags + "&fav=" + myFav;
        } else {
            url = NetConfig.CATEGORY_MORE + "?tags=" + tags;
        }


        OkHttpUtils.postString()
                .url(url)
                .content(str)
                .addHeader("Content-Type", "application/json")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        CategoryMoreBean packlist = gson.fromJson(response, CategoryMoreBean.class);
                        int code = packlist.getCode();
                        List<CategoryListBean.DatasBean.ArticlesBean> itemListharticle;


                        if (code == 200) {
                            itemListharticle = packlist.getDatas();

                            if (itemListharticle.size() > 0) {
                                mDataAdapter.addAll(itemListharticle);
                                is_end = false;
                                mRecyclerView.refreshComplete(10);
                            } else {
                                is_end = true;
                                mRecyclerView.refreshComplete(10);

                            }


                        }
                    }
                });
    }
}
